package cn.gzzhome.utils

/**
 * 用于组装参数
 */
class CommandParam {
    def values = []
    Closure makeMethod

    String name

    String description

    boolean require

    CommandParam(Closure makeMethod) {
        this.makeMethod = makeMethod
        makeMethod.delegate = this
    }

    /**
     *
     * @param name 描述
     * @param makeMethod 构建方法
     */
    CommandParam(String name, Closure makeMethod) {
        this(makeMethod)
        this.name = name
    }

    CommandParam(String name, String description, Closure makeMethod) {
        this(name, makeMethod)
        this.description = description
    }

    CommandParam(String name, String description, Closure makeMethod, boolean require) {
        this(name, description, makeMethod)
        this.require = require
    }

    /**
     * 可以使用操作符 <<
     * @param obj
     * @return
     */
    def leftShift(obj) {
        if (obj != null) {
            if (List.class.isAssignableFrom(obj.getClass())) {
                obj.each {
                    if (it != null) {
                        values += it
                    }
                }
            } else {
                values += obj
            }
        }
    }

    /**
     * 可以使用操作符 =
     * @param obj
     * @return
     */
    def set(obj) {
        leftShift(obj)
    }

    /**
     * 可以直接获取值
     * @return
     */
    def get(){
        return this
    }

    String build() {
        if (require && !values) {
            throw new RuntimeException("参数${name}必填！")
        }
        makeMethod()
    }

    def print() {
        println(build())
    }

}